import { defineStore } from "pinia";
import {LoginCode,Login} from '@/api/login/index'
import type {loginData,userInfoRes,UserState} from '@/api/login/type.ts'
// pinia 仓库写法：组合式API、选择式API
const userInfoStore = defineStore("User", {
  // 拿数据->取数据->存数据
  state: ():UserState => {
    return {
        visiable:false, //控制登录组件的显示与隐藏
        code:'',//收到的验证码
        userInfo:JSON.parse(localStorage.getItem('userInfo') as string) || {}//用户信息
    };
  },
  actions: {
    //获取验证码
    async getCode(phone: string) {
      let result:any = await LoginCode(phone);
      if(result.code===200){
        //存得到的验证吗
        this.code=result.data
        return '成功'
      }else{
        return Promise.reject(new Error(result.message))
      }
    
    },
    //登录
    async userLogin(loginData:loginData) {
      let result:userInfoRes = await Login(loginData);
      if(result.code===200){
        this.userInfo=result.data
        //本地存储
        localStorage.setItem('userInfo',JSON.stringify(this.userInfo))
        return '成功'
      }else{
        return Promise.reject(new Error(result.message))
      }
    
    },
    //退出登录
    logout(){
      this.userInfo={
        name:'',
        token:''
      }
      localStorage.removeItem('userInfo')
    }
  },
  getters: {},
});
// 获取仓库的方法对外暴露
export default  userInfoStore;